package net.vkits.common.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * Created by ethan-liu on 2017/2/1.
 */
public final class JwtHelper {
    private static final Logger logger = LoggerFactory.getLogger(JwtHelper.class);

    private static String key = "ytgkwehfklsjkldfgvjwkeghwrjhgasdjkfmnlwejhfwjigvsjkdlfcnwejhkfew";

    public static String createJWT(String cellPhone) {
        String token = Jwts.builder()
                // iss 该JWT的签发者
                .setIssuer("http://vkits.net")
                // aud 接收该JWT的一方
                .setAudience("Android")
                // sub 该JWT所面向的用户
                .setSubject(cellPhone)
                // iat 在什么时候签发的
                .setIssuedAt(Date.from(Instant.now()))
                // nbf token在此时间之前不能被接收处理
                .setNotBefore(Date.from(Instant.now()))
                // exp 什么时候过期
                .setExpiration(Date.from(Instant.now().plus(30, ChronoUnit.DAYS)))
                // 私有变量声明
                .claim("phone", cellPhone)
                .signWith(SignatureAlgorithm.HS512, key)
                .compact();
        return token;
    }

    public static Claims parseJWT(String token) throws ServletException {
            return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
    }

    //TODO something need handle, but I forget now.
    private Key getKey() {
        try (
                // Use file stream to load from file system or class.getResourceAsStream to load from classpath
                FileInputStream in = new FileInputStream("keystore.jks")
        ) {
            //Create Keystore: keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(in, "password".toCharArray());
            Key key = ks.getKey("selfsigned", "password".toCharArray());
            return key;
        } catch (KeyStoreException |
                NoSuchAlgorithmException |
                CertificateException |
                IOException |
                UnrecoverableKeyException e) {
            logger.error("Error: ", e);
        }
        return null;
    }

//    private Key getAKey() {
//        KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getKey("selfsigned", "password".toCharArray());
//        X509Certificate certificate = (X509Certificate) keyEntry.getCertificate();
//        return certificate.getPublicKey();
//    }
}
